/**
 * 21point
 *
 * outlook@China software studio
 * Copyright (c) 2008-2011. All Rights Reserved.
 * http://www.outlook.com
 */

package org.outlook.game.arithmetic;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * function:
 * @author watson  email: watson.wu@hotmail.com
 * @date 2011-3-21
 */
public class Main {

	private static final int DEFAULT_WIDTH = 800;
	private static final int DEFAULT_HEIGHT = 600;
	private static final int LOGIN_WIDTH = 360;
	private static final int LOGIN_HEIGHT = 278;
	
	private static final List<Poker> LIST = new ArrayList<Poker>(52);
	private int[] nums = new int[4];
	private int[] suits = new int[4];
	
	private static final Random RANDOM = new Random();
	
	private JFrame frame;
	private JPanel panel;
	private JPanel content;
	
	public Main() {
		super();
		frame = new JFrame("Dr. Watson athematic 24 Point ");
		initApp();
		startup();
	}

	private void initApp() {
		JFrame.setDefaultLookAndFeelDecorated(Boolean.FALSE);
		try {
			if(!loadResources()) {
				throw new Exception("Could not load resources");
			}
		} catch (Exception e) {
			panel = new JPanel();
			showMessage("Error", "Error occur : "+e.getMessage(), JOptionPane.ERROR_MESSAGE);
			System.exit(-1);
		}
	}

	private boolean loadResources() throws Exception {
		final URL imagesURL = PokerParser.getResourceInRoot("images/");
		File imagesDir = new File(imagesURL.toURI());
		if(imagesDir.isDirectory()) {
			String[] files = imagesDir.list(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String name) {
					if(null != name && ".jpg".equalsIgnoreCase(name.substring(name.lastIndexOf(".")))) {
						return true;
					}
					return false;
				}
				
			});
			if(files.length == 52) {
				for(String fileName : files) {
					Poker poker = PokerParser.parser(imagesURL, fileName);
					LIST.add(poker);
				}
				imagesDir = null;
				return true;
			}
		}
		imagesDir = null;
		
		return false;
	}

	public void startup() {
		panel = new JPanel();
		panel.setLayout(new BorderLayout());
		
		JTextArea textArea = new JTextArea(10, 80);
		textArea.setTabSize(10);
		textArea.setFont(new Font("DIALOG", Font.BOLD, 16));
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		textArea.setText("\t游戏规则\t\n\n    1. 将扑克代表的数字运用四则运算使其结果为24；\n    2. A代表1, J,Q,K代表10, 其他按字面数值；不论花色；\n    3. 整数运算, 不使用浮点数;");
		panel.add(new JScrollPane(textArea), BorderLayout.NORTH);
		
		JButton button = new JButton("开始");
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				panel.removeAll();
				panel.updateUI();
				start();
			}
			
		});
		panel.add(button, BorderLayout.SOUTH);

		frame.add(panel);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setPreferredSize(new Dimension(LOGIN_WIDTH, LOGIN_HEIGHT));
		focus(LOGIN_WIDTH, LOGIN_HEIGHT);
		frame.pack();
		frame.setVisible(Boolean.TRUE);
	}

	private void start() {
		int width = PokerParser.POKER_WIDTH*2+30;
		int height = PokerParser.POKER_HEIGHT*2+80;
		frame.setPreferredSize(new Dimension(width, height));
		focus(width, height);
		frame.pack();
		content = new JPanel(new GridLayout(2, 2));
		
		JButton hitBt = new JButton("Hand");
		JButton passBt = new JButton("Pass");
		JPanel btsPanel = new JPanel();
		btsPanel.add(hitBt);
		btsPanel.add(passBt);
		
		Collections.shuffle(LIST);
		getPoker();
		
		panel.add(content, BorderLayout.CENTER);
		panel.add(btsPanel, BorderLayout.SOUTH);
		panel.updateUI();
		
		hitBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				getPoker();
				content.updateUI();
			}
			
		});
		
		passBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if(Mathematician.checkIfSumIs24(nums)) {
					String result = Mathematician.getLast24Arithmetic();
					showMessage("Tips", result, JOptionPane.INFORMATION_MESSAGE);
				}
				getPoker();
				content.updateUI();
			}
			
		});
	}

	private void getPoker() {
		content.removeAll();
		content.updateUI();
		for(int i=0; i<4; i++) {
			Poker poker = getRandomPoker();
			nums[i] = poker.getNum();
			suits[i] = poker.getSuit();
			content.add(poker.getImage());
		}
	}

	private Poker getRandomPoker() {
		final int n = 51-content.getComponentCount();
		final int index = RANDOM.nextInt(n);
		Collections.swap(LIST, index, n);
		return LIST.get(n);
	}

	private void focus(int width, int height) {
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Dimension size = toolkit.getScreenSize();
		if(width<1)
			width = DEFAULT_WIDTH;
		if(height<1)
			height = DEFAULT_HEIGHT;
		if(size.getWidth()<width) {
			height *= size.getWidth()/width;
			width = (int)size.getWidth();
		}
		if(size.getHeight()<height) {
			height *= size.getWidth()/width;
			width = (int)size.getWidth();
		}
		frame.setLocation(((int) size.getWidth() - width) / 2, ((int) size.getHeight() - height) / 2);
	}
	
	public void showMessage(String title, String message, int messageType) {
		JOptionPane.showMessageDialog(panel, new String[] { message },
				title, messageType);
	}
	
	public static void main(String[] args) {
		new Main();
	}

}
